package com.gxuwz.prrs.interceptor;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.IOException;

import com.google.gson.reflect.TypeToken;
import com.gxuwz.prrs.bean.CommonResponse;
import com.gxuwz.prrs.constant.HttpCodeConstants;
import com.gxuwz.prrs.utils.BaseApplication;
import com.gxuwz.prrs.utils.NavigationUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.gxuwz.prrs.utils.RequestUtils.GSON;

/**
 * token拦截器
 */

public class RequestInterceptor implements Interceptor {

	@Override
	public Response intercept(Chain chain) throws IOException {
		SharedPreferences sharedPreferences = BaseApplication.getContext().getSharedPreferences("token", Context.MODE_PRIVATE);
		String token = sharedPreferences.getString("token", null);
		Request.Builder builder = chain.request()
				.newBuilder();
		if (token != null) {
			builder.addHeader("authorization", token);
		}
		Request request = builder.build();
		Response response = chain.proceed(request);
		int responseCode = response.code();
		ResponseBody body = response.body();
		if (HttpCodeConstants.SUCCESS.equals(responseCode)) {
			if (body != null) {
				String string = body.string();
				CommonResponse<Object> commonResponse = GSON.fromJson(string, new TypeToken<CommonResponse<Object>>() {
				}.getType());
				Response newResponse = response.newBuilder()
						.body(ResponseBody.create(string, body.contentType()))
						.build();
				Integer code = commonResponse.getCode();
				if (HttpCodeConstants.TO_LOGIN.equals(code)) {
					NavigationUtils.redirectToLoginActivity(BaseApplication.getContext(),null);
				}
				return newResponse;
			}
		} else if (HttpCodeConstants.FAIL.equals(responseCode)) {

		}
		return response;
	}
}
